﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Carozos.DALC
{
    public class SqlDataAccess
    {
        SqlConnection conn;
        public SqlDataAccess()
        {
            if (conn == null)
            {
                conn = new SqlConnection();
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["carozos"].ConnectionString;
            }
        }

        public SqlCommand createCommand(string sql)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            return cmd;
        }

        public SqlCommand createCommandSP(string sp)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = sp;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;
            return cmd;
        }

        public void addInParameter(SqlCommand cmd, string nombre, object value)
        {
            cmd.Parameters.AddWithValue(nombre, value);
        }

        public void executeNonQuery(SqlCommand cmd)
        {
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public int executeScalar(SqlCommand cmd)
        {
            int rpt =0;
            try
            {
                conn.Open();
                rpt = Convert.ToInt32(cmd.ExecuteScalar());
                conn.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
            return rpt;
        }

        public SqlDataReader executeReader(SqlCommand cmd)
        {
            conn.Open();
            SqlDataReader r = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            return r;
        }
    }
}
